package com.hdyg.sixg.httpUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hdyg.sixg.R;
import com.hdyg.sixg.activity.common.BaseActivity;
import com.hdyg.sixg.activity.common.AppManager;
import com.hdyg.sixg.activity.mine.CompleteInfoActivity;
import com.hdyg.sixg.entry.BaseBean;
import com.hdyg.sixg.httpUtil.okhttp.ParameterizedTypeImpl;
import com.hdyg.sixg.mvp.base.BaseUrl;
import com.hdyg.sixg.ui.CustomProgressDialog;
import com.hdyg.sixg.util.JsonUtil;
import com.hdyg.sixg.util.LogUtils;
import com.hdyg.sixg.util.ToastUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 回调
 *
 * @author CZB
 * @time 2018/7/5 14:55
 */
public abstract class HttpCallback<Result> implements ICallback {
    private CustomProgressDialog loaddingDialog;
    private Activity activity;

    /**
     * 无参构造函数
     */
    protected HttpCallback() {
        activity = AppManager.getAppManager().currentActivity();
    }

    /**
     * 有参构造函数[是否有加载进度条]
     *
     * @param isShowLoadding true：显示加载进度条；false：不显示加载进度条
     */
    public HttpCallback(boolean isShowLoadding) {
        activity = AppManager.getAppManager().currentActivity();
        if (isShowLoadding && (loaddingDialog == null) && !activity.isDestroyed()) {
            loaddingDialog = new CustomProgressDialog(activity, R.style.loading_dialog);
            loaddingDialog.show();
        }
    }

    /**
     * 泛型 Result 解析成功时回调
     *
     * @param result 泛型 回调的实体
     */
    public abstract void onSuccess(Result result);

    /**
     * 请求失败回调
     *
     * @param code  错误码
     * @param error 错误消息
     */
    public abstract void onFail(String code, String error);


    /**
     * 失败回调
     *
     * @param error
     */
    @Override
    public void onFail(String error) {
        hideProgress();
        LogUtils.e("####### onError：" + error);
        //
        onFail(null, error);
    }

    /**
     * 成功回调
     *
     * @param result
     */
    @Override
    public void onSuccess(String result) {
        hideProgress();
        BaseBean baseBean = null;
        LogUtils.d("####### onSuccess：" + result);
        // 解析 BaseBean
        try {
            baseBean = JsonUtil.parseJsonWithGson(result, BaseBean.class);
        } catch (JsonSyntaxException e) {
            onFail("json异常==");
        }
        if (baseBean == null) return;
        // 根据回调的状态处理
        switch (baseBean.getStatus()) {
            case BaseUrl.SUCCESS:   // 成功获取
                BaseBean<Result> data;
                Type type = getClass().getGenericSuperclass();
                if (type instanceof ParameterizedType) {
                    Type[] types = ((ParameterizedType) type).getActualTypeArguments();
                    Type ty = new ParameterizedTypeImpl(BaseBean.class, new Type[]{types[0]});
                    data = JsonUtil.createGson().fromJson(result, ty);
                    if (baseBean.getData() == null) {
                        ToastUtil.show(baseBean.getMessage());
                    }
                    onSuccess(data.getData());
                } else {
                    data = JsonUtil.createGson().fromJson(result, BaseBean.class);
                    onSuccess((Result) data.getMessage());
                }
                break;
            case BaseUrl.UN_TOKEN:  // token 失效(抢登)
                // 发送广播
                Intent intent = new Intent(BaseActivity.UN_TOKEN_BROCAST);
                AppManager.getAppManager().currentActivity().sendBroadcast(intent);
                break;
            case BaseUrl.COMPLETE_INFO:  // 完善资料
                ToastUtil.show(baseBean.getMessage());
                AppManager.getAppManager().currentActivity().finish();
                AppManager.getAppManager().startActivity(CompleteInfoActivity.class);
                break;
            case BaseUrl.FAIL:  // 获取失败
                onFail(null, baseBean.getMessage());
                break;
            default:
                onFail(baseBean.getStatus(), baseBean.getMessage());
                break;
        }
    }

    /**
     * 获取泛型 Result 的类[实际的实体类]
     *
     * @param object
     * @return
     */
    public static Class<?> analysisClassInfo(Object object) {
        // 使用反射机制获取object所有上下文中使用的类的名字
        Type genType = object.getClass().getGenericSuperclass();
        // 将获得的genType强转放在Type数组中
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];
    }

    /**
     * 关闭进度条
     */
    @SuppressLint("NewApi")
    public void hideProgress() {
        if (loaddingDialog != null) {
            if (loaddingDialog.isShowing()) { //check if dialog is showing.

                //get the Context object that was used to great the dialog
                Context context = ((ContextWrapper) loaddingDialog.getContext()).getBaseContext();

                //if the Context used here was an activity AND it hasn't been finished or destroyed
                //then dismiss it
                if (context instanceof Activity) {
                    if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed())
                        loaddingDialog.dismiss();
                } else //if the Context used wasnt an Activity, then dismiss it too
                    loaddingDialog.dismiss();
            }
            loaddingDialog = null;
        }
    }
}
